import { api } from './base/api'
import { ApiProxy } from './base/ApiProxy'
import { configs } from './base/configs'
import { utils } from './base/utils'
import { storage } from './helpers/storage'

let app: typeof appContext

ApiProxy.basePath = ''
ApiProxy.authErrorHandler = () => {
  app.logout(() => {
    utils.jump('home').redirect({})
  })
}

let globalData: GlobalData = {
  user: null,
}

let appContext = {
  globalData,

  login(callback: () => void) {
    // 调用微信登录接口
    if (globalData.user && globalData.user.openid) {
      console.log('** skip register for user data exists')
      if (configs.skipAuthCheck) {
        return callback()
      }
      callback()
    } else {
      if (configs.skipAuthCheck) {
        callback()
        return
      }
      console.error('** do login')
      wx.login({
        success: ({ code }) => {
          if (!code) {
            console.error('登录失败, 错误消息')
            utils.showFailToast('登录失败')
          }
          wx.getUserInfo({
            success: ({ iv, encryptedData }) => {
              api.wxappAuth(code, iv, encryptedData).success(({ data: { user } }) => {
                globalData.user = user
                ApiProxy.accessToken = user.token
                storage.set({ user }, callback)
              }).failOrError(() => {
                setTimeout(() => {
                  this.login(callback)
                }, 1000)
              })
            },
            fail: ({ errMsg }) => {
              console.error(`get user info data error, :${errMsg}`)
              utils.showHintToast('用户权限认证')
            }
          })
        },
        fail: ({ errMsg }) => {
          console.error('调用login接口失败 error:', errMsg)

        }
      })
    }
  },

  logout(callback?: () => void) {
    // 此api用于调试，正常逻辑中不会调用
    console.log('logging out')
    globalData.user = null
    storage.set({ user: null }, callback)
  }
}

export type GlobalContext = typeof appContext

App({
  ...appContext,
  onLaunch() {
    console.log('App launched')
    app = this
  }
})
